package org.arl.modem.transportARQ;

import org.arl.modem.InputPDU;
import org.arl.modem.OutputPDU;

/**
 * Object class for transport layer packet
 * 
 * @author rohit
 * 
 */
public class TransportPacket {

	public int messageType; // e.g. DATA(0),ACK(1),EOF(2)
	public int messageLength;
	public int packetId;
	public int blockId;
	public int blockSize;
	public byte[] messageData = null;
	public int src;
	public int dest;

	/**
	 * Default Constructor
	 */
	public TransportPacket() {

	}

	/**
	 * Encode the Transport layer packet
	 * 
	 * @return Byte stream of encoded packet
	 */
	public byte[] encode() {
		byte[] buf;
		// System.out.println("Encoding Started");

		OutputPDU pdu = new OutputPDU(messageLength + 7);
		pdu.write8(messageType);
		pdu.write8(messageLength);
		pdu.write8(packetId);
		pdu.write8(blockId);
		pdu.write8(blockSize);
		pdu.write8(src);
		pdu.write8(dest);
		pdu.write(messageData);
		buf = pdu.toByteArray();
		// System.out.println(messageType + ":" + messageLength + ":" + packetId
		// + ":" + blockId + ":" + blockSize + ":" + src + ":" + dest
		// + ":" + new String(messageData));
		// System.out.println("buf length:" + buf.length);
		// System.out.println("pdu length:" + pdu.size());
		// System.out.println("Encoding finished");
		return buf;
	}

	/**
	 * Decode the Byte stream into Packet
	 * 
	 * @param Byte
	 *            stream
	 * @return result
	 */
	public boolean decode(byte[] buf) {
		// System.out.println("Decoding Started");
		// System.out.println("To be decoded packet to transport layer:"
		// + new String(buf));

		InputPDU inpdu = new InputPDU(buf);
		// System.out.println("buffer length receiving:" + buf.length);
		this.messageType = inpdu.read8u();
		this.messageLength = inpdu.read8u();
		this.packetId = inpdu.read8u();
		this.blockId = inpdu.read8u();
		this.blockSize = inpdu.read8u();
		this.src = inpdu.read8u();
		this.dest = inpdu.read8u();
		// System.out.println("remaining data before:" + inpdu.available());
		this.messageData = new byte[messageLength];
		// FIXME :Rohit :08-Oct-2011 : if data is not read correctly error
		// handling should be done

		inpdu.read(this.messageData);
		// System.out.println(messageType + ":" + messageLength + ":" + packetId
		// + ":" + blockId + ":" + blockSize + ":" + src + ":" + dest
		// + ":" + new String(messageData));
		// System.out.println("remaining data after:" + inpdu.available());
		// System.out.println("Decoding finished");
		return true;
	}

}
